<?php declare(strict_types=1);

namespace PinWuYun\domain\dao;

use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use PinWuYun\domain\models\ConfigModel;

/**
 * Creator : zhiJie
 * Date: 2021/7/6
 */
class ConfigDao
{
    public function getConfig(string $key)
    {
        return ConfigModel::query()->where([
            'key' => $key,
            'is_deleted' => ConfigModel::DELETE_FALSE
        ])->value('value');
    }

    /**
     * 添加一条配置
     * @throws Exception
     */
    public function addConfig(string $key, string $value): ConfigModel
    {
        $num = ConfigModel::query()->where([
            'key' => $key,
            'is_deleted' => ConfigModel::DELETE_FALSE
        ])->count();
        if($num) {
            throw new Exception($key.'已存在,无法重复添加');
        }

        $model = new ConfigModel();
        $model->setRawAttributes([
            'key' => $key,
            'value' => $value
        ])->save();

        return $model;
    }

    /**
     * 设置一条配置
     * @param string $key
     * @param string $value
     * @return bool
     * @throws Exception
     */
    public function setConfig(string $key, string $value): bool
    {
        $model = ConfigModel::query()->where([
            'key' => $key,
            'is_deleted' => ConfigModel::DELETE_FALSE
        ])->first();
        if($model) {
            throw new Exception('配置不存在,key:'.$key);
        }
        $model->setAttribute('value',$value);
        return $model->save();
    }

    /**
     * 获取多个配置信息
     * @param array $keys ['key1', 'key2'...]
     * @return array
     */
    public function getConfigGroup(array $keys): array
    {
        return ConfigModel::query()
            ->whereIn('key', $keys)
            ->where('is_deleted' ,'=', ConfigModel::DELETE_FALSE)
            ->select(['key','value'])->get()->toArray();
    }


    /**
     * 修改多个配置
     * @param array $configGroup [['key'=>'', 'value'=>'']]
     */
    public function setConfigGroup(array $configGroup): bool
    {
        DB::beginTransaction();
        try{
            foreach ($configGroup as $item) {
                $model = ConfigModel::query()->where([
                    ['key' => $item['key']],
                    ['is_deleted' => ConfigModel::DELETE_FALSE]
                ])->first();
                if(!$model) {
                    continue;
                }
                $model->setAttribute(
                    'value', $item['value']
                );
                $model->save();
            }
            DB::commit();
            return true;
        } catch (Exception $e) {
            DB::rollBack();
            return false;
        }
    }
}